package com.example.wac.listener;

import com.alibaba.fastjson.JSON;
import com.example.wac.constant.Constant;
import com.example.wac.mail.SendMail;
import com.example.wac.mail.ToEmail;
import com.example.wac.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyContext;
import org.apache.rocketmq.client.consumer.listener.ConsumeOrderlyStatus;
import org.apache.rocketmq.client.consumer.listener.MessageListenerOrderly;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

/**
 * 注册消费的监听
 * @description
 * @author wuancheng
 * @date 2021-07-28 14:25:00
 */

@Component
@Slf4j
public class MqListener implements MessageListenerOrderly {
    @Autowired
    SendMail sendMail;

    @Autowired
    EmailService emailService;

    @Override
    public ConsumeOrderlyStatus consumeMessage(List<MessageExt> list, ConsumeOrderlyContext consumeOrderlyContext) {
        // messages中只收集同一个topic，同一个tag，并且key相同的message
        // 会把不同的消息分别放置到不同的队列中
            for (Message msg : list) {
                //消费者获取消息 这里只输出 不做后面逻辑处理
                    switch (msg.getTags()){
                        case "mailTag":
                            try {
                                MDC.put(Constant.TRANSACTION_ID, UUID.randomUUID().toString());
                                String body = new String(msg.getBody(), "utf-8");
                                log.info("Consumer-获取消息-主题topic为={}, 消费消息为={}", msg.getTopic(),body);
                                //反序列化成对象
                                ToEmail email = JSON.parseObject(body, ToEmail.class);
                                if (email != null){
                                    sendMail.asyncCommonEmail(email);
                                    //邮件发送成功保存记录
                                    emailService.save(email);
                                }
                            } catch (UnsupportedEncodingException e) {
                                e.printStackTrace();
                            }
                        case "":

                    }
            }
        return ConsumeOrderlyStatus.SUCCESS;
    }
}